# To change this template, choose Tools | Templates
# and open the template in the editor.
from game.gui.widget import Widget
import pygame

class Container(Widget):
    def __init__(self, **args):
        Widget.__init__(self, **args)
        self.children = []

        self.canvas = pygame.Surface((self.rect[2], self.rect[3])).convert()

    def add_child(self, ch, zindex=0):
        ch.parent = self
        i = 0
        for z, w in self.children:
            i += 1
            if z > zindex:
                self.children.insert(i, (zindex, ch))
                break
        if i == len(self.children):
            self.children.append((zindex, ch))

        self.make_dirty()

    def remove_child(self, ch):
        for z, w in self.children:
            if w == ch:
                self.children.remove((z, w))
        self.make_dirty()


    def draw(self, canvas, area=None):
        if area is None:
            area = self.rect
        if self.dirty:
            self.canvas = pygame.Surface((area[2], area[3])).convert()
            self.canvas.fill((255,0,255))
            self.canvas.set_colorkey((255,0,255))
            for z, w in reversed(self.children):
                w.draw(self.canvas)
            canvas.blit(self.canvas, (area[0], area[1]))
            self.dirty = 0
        else:
            canvas.blit(self.canvas, (area[0], area[1]))

    def receive(self, dat, evt):
        for z, w in self.children:
            if w.receive(dat, evt) == 1:
                return 1
        return 0
